#include<iostream>
#include<pthread.h>
#include<cstring>
#include<string>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<unistd.h>
#include"Thread_Pool.hpp"
#include"Task.hpp"




void usage(std::string proc)
{
    std::cout << proc << " bind_port" << std::endl;
}

int main(int argc , char* argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        return 1;
    }
    //create listen_sock
    int listen_sock = socket(AF_INET,SOCK_STREAM,0);
    if(listen_sock < 0)
    {
        std::cerr << "socket error  " << errno << std::endl;
    }

    //bind
    struct sockaddr_in local;
    memset(&local,0,sizeof local);
    local.sin_family = AF_INET;
    local.sin_port = htons(atoi(argv[1]));
    local.sin_addr.s_addr = INADDR_ANY;
    if(bind(listen_sock,(struct sockaddr*)&local,sizeof(local)) < 0)
    {
        std::cerr << "bind error  " << errno << std::endl;
    }

    //listen
    if(listen(listen_sock,5) < 0)
    {
        std::cerr << "listen error  " << errno << std::endl;
    }

    //accept 
    wyl::ThreadPool<wyl::Task>* tp  = new wyl::ThreadPool<wyl::Task>();
    tp->ThreadPollInit();
    while(true)
    {
        struct sockaddr_in cli;
        memset(&cli,0,sizeof cli);
        socklen_t len;
        int new_sock = accept(listen_sock,(struct sockaddr*)&cli,&len);
        if(new_sock < 0 )
        {
            continue;
        }
        std::cout << "get a connect " << std::endl;
        //提供服务
        std::string cli_ip = inet_ntoa(cli.sin_addr);
        wyl::Task tt(new_sock,cli_ip);
        tp->push(tt);
    }

}